from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class BasePage:
    def __init__(self, webdriver):
        self.webdriver = webdriver

    def find_element(self, by, locator):
        return self.webdriver.find_element(by, locator)

    def click_element(self, element):
        element.click()

    def input_text(self, element, text):
        element.send_keys(text)

    def wait_for_angular_ready(self):
        """等待AngularJS完成渲染"""
        # 等待AngularJS加载完成
        WebDriverWait(self.webdriver, timeout=5).until(
            lambda d: d.execute_script("return angular.element(document).injector().get('$http').pendingRequests.length === 0;")
        )
    
    def wait_element(self, BY, locator, timeout):
        # 步骤1：等待元素存在
        element = WebDriverWait(self.webdriver, timeout).until(
            EC.presence_of_element_located(BY, locator=locator)
        )
        # 步骤2：等待文本加载
        WebDriverWait(self.webdriver, timeout).until(
            lambda d: element.text.strip() != ""
        )
    
